namespace SimpleWebServices.Xml
{
    using System;
    using System.Diagnostics.CodeAnalysis;
    using System.Xml;
    using System.Xml.XPath;

    public static class XmlDocumentExtensionMethods
    {
        [SuppressMessage("Microsoft.Design", "CA1059:MembersShouldNotExposeCertainConcreteTypes", MessageId = "System.Xml.XmlNode", Justification = "This method intentionally returns a concrete type.")]
        public static XmlAttribute ToXmlAttribute(this XmlDocument document, string name, string value)
        {
            if (null == document)
            {
                throw new ArgumentNullException("document");
            }
            else if (null == name)
            {
                throw new ArgumentNullException("name");
            }

            XmlAttribute result = null;

            if (null != value)
            {
                result = document.CreateAttribute(name);
                result.Value = value;
            }

            return result;
        }

        [SuppressMessage("Microsoft.Design", "CA1059:MembersShouldNotExposeCertainConcreteTypes", MessageId = "System.Xml.XmlNode", Justification = "This method intentionally returns a concrete type.")]
        public static XmlNode ToXmlNode(this XmlDocument document, string name, IXPathNavigable value)
        {
            if (null == document)
            {
                throw new ArgumentNullException("document");
            }
            else if (null == name)
            {
                throw new ArgumentNullException("name");
            }

            XmlNode result = document.CreateNode(XmlNodeType.Element, name, null);

            if (null != value)
            {
                result.InnerXml = value.CreateNavigator().OuterXml;
            }

            return result;
        }

        [SuppressMessage("Microsoft.Design", "CA1059:MembersShouldNotExposeCertainConcreteTypes", MessageId = "System.Xml.XmlNode", Justification = "This method intentionally returns a concrete type.")]
        public static XmlNode ToXmlNode(this XmlDocument document, string name, string value)
        {
            if (null == document)
            {
                throw new ArgumentNullException("document");
            }
            else if (null == name)
            {
                throw new ArgumentNullException("name");
            }

            XmlNode result = document.CreateNode(XmlNodeType.Element, name, null);

            if (null != value)
            {
                result.InnerText = value;
            }

            return result;
        }
    }
}